const QuestionSet = require('../models/QuestionSet.js')
const QuestionSetItem = require('../models/QuestionSetItem.js')
const Question = require('../models/Question.js')
const User = require('../models/User.js')
const { Op } = require('sequelize');
const sequelize = require('../db/db');
const { sendResponse, sendListResponse } = require('../utils/response');
const { getTimestamp, getTwoDigits, formatObject } = require('../utils/common');

/**
 * 创建题库
 * @param {Object} req - Express请求对象
 * @param {Object} res - Express响应对象
 */
const createQuestionSet = async (req, res) => {
  const transaction = await sequelize.transaction();
  try {
    const { name, description, userId } = req.body;

    // 验证参数
    if (!name) {
      return sendResponse(res, 500, '题库名称不能为空');
    }

    if (!userId) {
      return sendResponse(res, 500, '用户ID不能为空');
    }

    // 生成题库ID
    const id = "194" + getTimestamp() + getTwoDigits();

    // 创建题库
    const questionSet = await QuestionSet.create({
      id,
      name,
      description,
      user_id: userId,
      question_count: 0,
      create_time: new Date(),
    }, { transaction });

    await transaction.commit();

    // 返回创建的题库信息
    sendResponse(res, 200, '题库创建成功', formatObject({
      id: questionSet.id,
      name: questionSet.name,
      description: questionSet.description,
      questionCount: questionSet.question_count,
      createTime: questionSet.create_time,
    }));
  } catch (error) {
    await transaction.rollback();
    console.error('创建题库失败:', error);
    sendResponse(res, 500, '创建题库失败', error.message);
  }
};

/**
 * 获取题库列表
 * @param {Object} req - Express请求对象
 * @param {Object} res - Express响应对象
 */
const getQuestionSetList = async (req, res) => {
  try {
    const { page = 1, pageSize = 10, name, userId } = req.query;

    if (!userId) {
      return sendResponse(res, 500, '用户ID不能为空');
    }

    const offset = (parseInt(page) - 1) * parseInt(pageSize);

    // 构建查询条件
    const whereCondition = {
      user_id: userId,
    };

    if (name) {
      whereCondition.name = {
        [Op.like]: `%${name}%`
      };
    }

    // 查询题库总数
    const total = await QuestionSet.count({
      where: whereCondition
    });

    // 查询题库列表
    const questionSets = await QuestionSet.findAll({
      where: whereCondition,
      limit: parseInt(pageSize),
      offset: parseInt(offset),
      order: [['create_time', 'DESC']]
    });

    // 格式化返回数据
    const formattedQuestionSets = questionSets.map(set => formatObject({
      id: set.id,
      name: set.name,
      description: set.description,
      questionCount: set.question_count,
      createTime: set.create_time,
      updateTime: set.update_time,
    }));

    sendListResponse(res, 200, '获取题库列表成功', formattedQuestionSets, total);
  } catch (error) {
    console.error('获取题库列表失败:', error);
    sendResponse(res, 500, '获取题库列表失败', error.message);
  }
};

/**
 * 获取题库详情
 * @param {Object} req - Express请求对象
 * @param {Object} res - Express响应对象
 */
const getQuestionSetDetail = async (req, res) => {
  try {
    const { id } = req.params;
    const { userId } = req.query;

    if (!id) {
      return sendResponse(res, 500, '题库ID不能为空');
    }

    if (!userId) {
      return sendResponse(res, 500, '用户ID不能为空');
    }

    // 查询题库详情
    const questionSet = await QuestionSet.findOne({
      where: {
        id,
        user_id: userId,
      }
    });

    if (!questionSet) {
      return sendResponse(res, 500, '题库不存在');
    }

    // 查询题库中的题目
    const items = await QuestionSetItem.findAll({
      where: {
        set_id: id
      },
      include: [{
        model: Question,
        as: 'question',
        attributes: ['id', 'content', 'options', 'difficulty', 'category_id']
      }],
      order: [['order_num', 'ASC']]
    });

    // 格式化题目数据
    const questions = items.map(item => formatObject({
      id: item.question.id,
      content: item.question.content,
      options: item.question.options,
      difficulty: item.question.difficulty,
      categoryId: item.question.category_id,
      orderNum: item.order_num
    }));

    // 格式化题库详情
    const formattedQuestionSet = formatObject({
      id: questionSet.id,
      name: questionSet.name,
      description: questionSet.description,
      questionCount: questionSet.question_count,
      createTime: questionSet.create_time,
      updateTime: questionSet.update_time,
      questions
    });

    sendResponse(res, 200, '获取题库详情成功', formattedQuestionSet);
  } catch (error) {
    console.error('获取题库详情失败:', error);
    sendResponse(res, 500, '获取题库详情失败', error.message);
  }
};

/**
 * 更新题库信息
 * @param {Object} req - Express请求对象
 * @param {Object} res - Express响应对象
 */
const updateQuestionSet = async (req, res) => {
  try {
    const { id, name, description, userId } = req.body;

    if (!userId) {
      return sendResponse(res, 500, '用户ID不能为空');
    }

    // 验证参数
    if (!name) {
      return sendResponse(res, 500, '参数错误: 题库名称不能为空');
    }

    // 查询题库是否存在
    const questionSet = await QuestionSet.findOne({
      where: {
        id,
        user_id: userId,
      }
    });

    if (!questionSet) {
      return sendResponse(res, 500, '题库不存在');
    }

    // 更新题库信息
    await questionSet.update({
      name,
      description,
      update_time: new Date()
    });

    // 返回更新后的题库信息
    sendResponse(res, 200, '题库更新成功', formatObject({
      id: questionSet.id,
      name: questionSet.name,
      description: questionSet.description,
      questionCount: questionSet.question_count,
      createTime: questionSet.create_time,
      updateTime: questionSet.update_time
    }));
  } catch (error) {
    console.error('更新题库失败:', error);
    sendResponse(res, 500, '更新题库失败', error.message);
  }
};

/**
 * 删除题库
 * @param {Object} req - Express请求对象
 * @param {Object} res - Express响应对象
 */
const deleteQuestionSet = async (req, res) => {
  try {
    const { id, userId } = req.query;

    if (!userId) {
      return sendResponse(res, 500, '用户ID不能为空');
    }

    // 查询题库是否存在
    const questionSet = await QuestionSet.findOne({
      where: {
        id,
        user_id: userId,
      }
    });

    if (!questionSet) {
      return sendResponse(res, 500, '题库不存在');
    }

    // 逻辑删除题库
    await questionSet.destroy()

    sendResponse(res, 200, '题库删除成功');
  } catch (error) {
    console.error('删除题库失败:', error);
    sendResponse(res, 500, '删除题库失败', error.message);
  }
};

/**
 * 添加题目到题库
 * @param {Object} req - Express请求对象
 * @param {Object} res - Express响应对象
 */
const addQuestionToSet = async (req, res) => {
  const transaction = await sequelize.transaction();
  try {
    const { setId, questionIdList, userId } = req.body;

    // 验证参数
    if (!setId || !questionIdList || !Array.isArray(questionIdList) || questionIdList.length === 0) {
      return sendResponse(res, 500, '参数错误: 题库ID和题目ID列表不能为空');
    }

    if (!userId) {
      return sendResponse(res, 500, '用户ID不能为空');
    }

    // 验证题库是否存在且归属当前用户
    const questionSet = await QuestionSet.findOne({
      where: {
        id: setId,
        user_id: userId,
      }
    });

    if (!questionSet) {
      return sendResponse(res, 500, '题库不存在或无访问权限');
    }

    // 验证题目是否存在
    const questions = await Question.findAll({
      where: {
        id: questionIdList
      }
    });

    // 找出不存在的题目ID
    const existingQuestionIds = questions.map(q => q.id);
    const nonExistingQuestionIds = questionIdList.filter(id => !existingQuestionIds.includes(id));

    if (nonExistingQuestionIds.length > 0) {
      return sendResponse(res, 500, `以下题目ID不存在: ${nonExistingQuestionIds.join(', ')}`);
    }

    // 检查题目是否已在题库中
    const existingItems = await QuestionSetItem.findAll({
      where: {
        set_id: setId,
        question_id: questionIdList
      }
    });

    const existingQuestionIdsInSet = existingItems.map(item => item.question_id);
    const newQuestionIds = questionIdList.filter(id => !existingQuestionIdsInSet.includes(id));

    if (newQuestionIds.length === 0) {
      return sendResponse(res, 500, '所有题目都已存在于题库中');
    }

    // 获取当前最大的orderNum
    const maxOrderResult = await QuestionSetItem.findOne({
      attributes: [[sequelize.fn('MAX', sequelize.col('order_num')), 'maxOrder']],
      where: { set_id: setId }
    });

    let startOrderNum = 0;
    if (maxOrderResult && maxOrderResult.getDataValue('maxOrder') !== null) {
      startOrderNum = maxOrderResult.getDataValue('maxOrder') + 1;
    }

    // 批量添加题目到题库
    const itemsToCreate = newQuestionIds.map((questionId, index) => {
      return {
        id: "197" + getTimestamp() + getTwoDigits(),
        set_id: setId,
        question_id: questionId,
        order_num: startOrderNum + index,
        create_time: new Date()
      };
    });

    await QuestionSetItem.bulkCreate(itemsToCreate, { transaction });

    // 更新题库题目数量
    await questionSet.increment('question_count', { by: newQuestionIds.length, transaction });
    await questionSet.update({ update_time: new Date() }, { transaction });

    await transaction.commit();
    sendResponse(res, 200, `成功添加${newQuestionIds.length}个题目到题库中`, {
      addedQuestionIds: newQuestionIds,
      skippedQuestionIds: existingQuestionIdsInSet
    });
  } catch (error) {
    await transaction.rollback();
    console.error('添加题目到题库失败:', error);
    sendResponse(res, 500, '添加题目到题库失败', error.message);
  }
};

/**
 * 从题库移除题目
 * @param {Object} req - Express请求对象
 * @param {Object} res - Express响应对象
 */
const removeQuestionFromSet = async (req, res) => {
  const transaction = await sequelize.transaction();
  try {
    const { setId, questionIdList, userId } = req.body;

    if (!userId) {
      return sendResponse(res, 500, '用户ID不能为空');
    }

    if (!setId) {
      return sendResponse(res, 500, '题库ID不能为空');
    }

    if (!questionIdList) {
      return sendResponse(res, 500, '题目ID列表不能为空');
    }

    // 解析questionIdList，可能是单个ID或数组
    let questionIds = [];
    if (typeof questionIdList === 'string') {
      // 如果是逗号分隔的字符串，拆分为数组
      if (questionIdList.includes(',')) {
        questionIds = questionIdList.split(',');
      } else {
        // 单个ID
        questionIds = [questionIdList];
      }
    } else if (Array.isArray(questionIdList)) {
      questionIds = questionIdList;
    }

    if (questionIds.length === 0) {
      return sendResponse(res, 500, '题目ID列表不能为空');
    }

    // 验证题库是否存在且归属当前用户
    const questionSet = await QuestionSet.findOne({
      where: {
        id: setId,
        user_id: userId,
      }
    });

    if (!questionSet) {
      return sendResponse(res, 500, '题库不存在或无访问权限');
    }

    // 检查题目是否在题库中
    const existingItems = await QuestionSetItem.findAll({
      where: {
        set_id: setId,
        question_id: questionIds
      }
    });

    if (existingItems.length === 0) {
      return sendResponse(res, 500, '没有找到要删除的题目');
    }

    // 获取实际找到的题目ID
    const foundQuestionIds = existingItems.map(item => item.question_id);
    // 找出请求中但不存在于题库中的题目ID
    const notFoundQuestionIds = questionIds.filter(id => !foundQuestionIds.includes(id));

    // 从题库批量移除题目
    await QuestionSetItem.destroy({
      where: {
        set_id: setId,
        question_id: foundQuestionIds
      },
      transaction
    });

    // 更新题库题目数量
    await questionSet.decrement('question_count', { by: foundQuestionIds.length, transaction });
    await questionSet.update({ update_time: new Date() }, { transaction });

    await transaction.commit();

    // 如果只删除一个题目，返回简单消息
    if (questionIds.length === 1) {
      if (foundQuestionIds.length === 1) {
        sendResponse(res, 200, '题目移除成功');
      } else {
        sendResponse(res, 500, '题目不存在于题库中');
      }
    } else {
      // 批量删除，返回详细信息
      if (notFoundQuestionIds.length > 0) {
        sendResponse(res, 200, `成功移除${foundQuestionIds.length}个题目，${notFoundQuestionIds.length}个题目不在题库中`, {
          removedQuestionIds: foundQuestionIds,
          notFoundQuestionIds: notFoundQuestionIds
        });
      } else {
        sendResponse(res, 200, `成功移除${foundQuestionIds.length}个题目`, {
          removedQuestionIds: foundQuestionIds
        });
      }
    }
  } catch (error) {
    await transaction.rollback();
    console.error('从题库移除题目失败:', error);
    sendResponse(res, 500, '从题库移除题目失败', error.message);
  }
};

/**
 * 更新题库中题目顺序
 * @param {Object} req - Express请求对象
 * @param {Object} res - Express响应对象
 */
const updateQuestionOrder = async (req, res) => {
  const transaction = await sequelize.transaction();
  try {
    const { setId } = req.params;
    const { orders, userId } = req.body; // 格式: [{questionId: 'xxx', orderNum: 1}, ...]

    if (!userId) {
      return sendResponse(res, 500, '用户ID不能为空');
    }

    // 验证参数
    if (!setId || !orders || !Array.isArray(orders)) {
      return sendResponse(res, 500, '参数错误: 题库ID和排序数据不能为空');
    }

    // 验证题库是否存在且归属当前用户
    const questionSet = await QuestionSet.findOne({
      where: {
        id: setId,
        user_id: userId,
      }
    });

    if (!questionSet) {
      return sendResponse(res, 500, '题库不存在或无访问权限');
    }

    // 更新题目顺序
    for (const order of orders) {
      const { questionId, orderNum } = order;
      if (!questionId) continue;

      await QuestionSetItem.update(
        { order_num: orderNum },
        {
          where: {
            set_id: setId,
            question_id: questionId
          },
          transaction
        }
      );
    }

    // 更新题库更新时间
    await questionSet.update({ update_time: new Date() }, { transaction });

    await transaction.commit();
    sendResponse(res, 200, '题目顺序更新成功');
  } catch (error) {
    await transaction.rollback();
    console.error('更新题目顺序失败:', error);
    sendResponse(res, 500, '更新题目顺序失败', error.message);
  }
};

module.exports = {
  createQuestionSet,
  getQuestionSetList,
  getQuestionSetDetail,
  updateQuestionSet,
  deleteQuestionSet,
  addQuestionToSet,
  removeQuestionFromSet,
  updateQuestionOrder
}; 